<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="关联用户" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入关联 用户"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="当前积分" prop="points">
        <el-input
          v-model="queryParams.points"
          placeholder="请输入当前积分"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['points:points:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['points:points:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['points:points:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['points:points:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="pointsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!--      <el-table-column label="${comment}" align="center" prop="id" />-->
      <el-table-column label="序号" type="index" width="50" align="center"/>
      <el-table-column label="用户id" align="center" prop="userId" v-if="showUserIdColumn"/>
      <el-table-column label="用户名" align="center" prop="userName" />
      <el-table-column label="当前积分" align="center" prop="points" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['points:points:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['points:points:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户积分账户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
<!--        <el-form-item label="用户名" prop="userId">-->
<!--          <el-input v-model="form.userName" placeholder="用户名" disabled />-->
<!--        </el-form-item>-->
        <el-form-item label="当前积分" prop="points">
          <el-input v-model="form.points" placeholder="请输入当前积分" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPoints, getPoints, delPoints, addPoints, updatePoints } from "@/api/points/points";
import { getUserById } from "@/api/system/user"; // 假设这是你的接口文件

export default {
  name: "Points",
  data() {
    return {
      showUserIdColumn: false, // 设置为 false，隐藏该列
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      pointsList: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: null,
        points: null,
        userId: null,
      },
      form: {},
      rules: {
        userName: [
          { required: true, message: "用户名不能为空", trigger: "blur" }
        ],
        points: [
          { required: true, message: "当前积分不能为空", trigger: "blur" }
        ],
      },
      userMap: {}, // 用户名与ID映射表
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询用户积分账户列表 */
    async getList() {
      this.loading = true;
      try {
        const response = await listPoints(this.queryParams);
        this.pointsList = response.rows;

        // 如果后端返回的数据中没有包含用户名，则需要额外请求
        if (!this.pointsList.some(point => point.userName)) {
          await this.loadUserNames(this.pointsList);
        }

        this.total = response.total;
      } catch (error) {
        console.error("Failed to fetch points list:", error);
      } finally {
        this.loading = false;
      }
    },
    /** 加载用户名 */
    async loadUserNames(points) {
      const userIds = points.map(item => item.userId).filter(userId => !this.userMap[userId]);
      if (userIds.length === 0) return;

      try {
        const responses = await Promise.all(userIds.map(id => getUserById(id)));
        responses.forEach(response => {
          const { id, username } = response.data; // 假设返回的对象中有id和username字段
          this.userMap[id] = username;
        });

        this.pointsList.forEach(point => {
          if (point.userId && this.userMap[point.userId]) {
            point.userName = this.userMap[point.userId];
          }
        });
      } catch (error) {
        console.error("Failed to fetch usernames:", error);
      }
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户积分账户";
    },
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getPoints(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改用户积分账户";
      });
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const operation = this.form.id ? updatePoints : addPoints;
          operation(this.form).then(() => {
            this.$modal.msgSuccess(`${this.form.id ? '修改' : '新增'}成功`);
            this.open = false;
            this.getList();
          }).catch(error => {
            console.error(`Failed to ${this.form.id ? 'update' : 'add'} points:`, error);
          });
        }
      });
    },
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除用户积分账户编号为"' + ids + '"的数据项？').then(() => {
        return delPoints(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleExport() {
      this.download('points/points/export', {
        ...this.queryParams
      }, `points_${new Date().getTime()}.xlsx`);
    },
    reset() {
      this.form = {
        id: null,
        userName: null,
        points: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    cancel() {
      this.open = false;
      this.reset();
    },
  },
};
</script>
